#include  <unistd.h>
#include  <sys/types.h>       /* basic system data types */
#include  <sys/socket.h>      /* basic socket definitions */
#include  <netinet/in.h>      /* sockaddr_in{} and other Internet defns */
#include  <arpa/inet.h>       /* inet(3) functions */
#include <netdb.h> /*gethostbyname function */

#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>

#define MAXLINE 4096

int main(int argc, char **argv)
{
    int                 sockfd, n;
    struct sockaddr_in  servaddr;
    char                buf[MAXLINE + 1];
    int                 port = 13;

    if (argc != 2) {
        printf("usage: a.out <IPaddress>\n");
        return EXIT_FAILURE;
    }

    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        printf("socket error.");
        return EXIT_FAILURE;
    }

    bzero(&servaddr, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_port = htons(port);
    if (inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0) {
        printf("inet_pton error");
        return EXIT_FAILURE;
    }

    if (connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) {
        perror("connect error");
        return -1;
    }

    while((n = read(sockfd, buf, MAXLINE)) > 0) {
        buf[n] = 0;
        if (fputs(buf, stdout) == EOF) {
            perror("fputs error");
            break;
        }
    }

    if (n < 0) 
        perror("read error");

    exit(0);
}

